import 'package:aichat_flutter_wallet/module/module_browser/viewmodel/we3_method.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/bottom_sheet_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';

import 'dapp_select_node_widget.dart';

class DappSelectNodeWidget extends StatefulWidget {
  String? title;
  String walletShortName;
  String url;
  DappSelectNodeWidget(
      {super.key,
      required this.url,
      this.title,
      required this.walletShortName});

  @override
  State<DappSelectNodeWidget> createState() => _DappSelectNodeWidgetState();
}

class _DappSelectNodeWidgetState extends State<DappSelectNodeWidget> {
  List<NodeInfo> _nodeList = [];
  int curIndex = 0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _nodeList = Web3MethodCall.getNodeList(widget.walletShortName);
    doInit();
  }

  setCurIndex(int index, dynamic blockMap) {
    if (curIndex == index) return;
    // setState(() {
    //   curIndex = index;
    // });
    var item = _nodeList[index];
    Map<String, dynamic> map = {};
    map['node'] = item;
    map['block'] = blockMap;
    Navigator.of(context).pop(map);
  }

  doInit() {
    int index = _nodeList.indexWhere((element) {
      return element.url == widget.url;
    });

    if (index != -1) {
      setState(() {
        curIndex = index;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return BottomSheetWidget(
      title: widget.title ?? 'Select Node',
      expand: false,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              height: 430.w,
              child: ListView.builder(
                  itemCount: _nodeList.length,
                  itemBuilder: (_, index) {
                    return DappNodeWidget(
                      node: _nodeList[index],
                      index: index,
                      onChange: setCurIndex,
                      isSelect: curIndex == index,
                    );
                  }),
            ),
            SizedBox(
              height: 10 + MediaQuery.of(context).padding.bottom,
            ),
          ],
        ),
      ),
    );
  }
}
